package com.cloudkinto.controller.orderrepair;


import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.service.dic.vo.dicBusinessItem.DicBusinessNewEntity;
import com.cloudkinto.service.orderrepair.vo.*;
import com.cloudkinto.service.product.ProductInfoService;
import com.cloudkinto.service.product.ProductStockRackService;
import com.cloudkinto.service.stock.StockRecordService;
import com.cloudkinto.service.stock.vo.record.StockRecordPageRes;
import com.cloudkinto.service.storage.StoragePositionService;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.cloudkinto.service.orderrepair.OrderRepairService;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.cloudkinto.base.BaseController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hua
 * @since 2023-06-14
 */
@RestController
@Api(tags = "维修管理模块")
@RequestMapping("/api/admin/OrderRepair")
public class OrderRepairController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(OrderRepairController.class);

    @Autowired
    private OrderRepairService service;
    @Autowired
    private StockRecordService stockRecordService;
    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private StoragePositionService storagePositionService;
    @Autowired
    private ProductStockRackService productStockRackService;

    @UserSessionRequired
    @GetMapping("/addInit")
    @ApiOperation(value = "新增初始化", notes = "新增初始化")
    public SingleResult addInit() {
        return service.addInit();
    }

    @UserSessionRequired
    @PostMapping("")
    @ApiOperation(value = "维修订单新增", notes = "维修订单新增")
    public SingleResult add(@RequestBody @Validated OrderRepairAddReq req) {
        Long userId = getCurrentUserId();
        service.add(req, userId);
        return SingleResult.success("新增成功", "");
    }


    @UserSessionRequired
    @GetMapping("/repairCategoryInit")
    @ApiOperation(value = "选择标签初始化", notes = "选择标签初始化")
    public SingleResult repairCategoryInit(Long companyId) {
        Map<String, Object> res = new HashMap<>();
        res.put("repairCategoryList", service.repairCategoryInit(companyId));
        return SingleResult.success(res);
    }

    @UserSessionRequired
    @PutMapping("/addOrUpdateCategory")
    @ApiOperation(value = "添加自定义标签", notes = "添加自定义标签")
    public SingleResult addOrUpdateCategory(@RequestBody @Validated DicBusinessNewEntity idAndNameEntity) {
        service.addOrUpdateCategory(idAndNameEntity);
        return SingleResult.success();
    }


    @UserSessionRequired
    @GetMapping("/stockRecordListPage")
    @ApiOperation(value = "选择部件初始化（分页）", notes = "选择部件初始化（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "keyword", value = "关键字搜索"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "页大小"),
            @ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "companyId", value = "公司id")})
    @ApiResponses({@ApiResponse(code = 200, message = "", response = StockRecordPageRes.class)})
    public PageResult<StockRecordPageRes> stockRecordListPage(HttpServletRequest request) {

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String shopId = request.getParameter("shopId");
        String storageId = request.getParameter("storageId");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        String productType = request.getParameter("productType");

        map.put("keyword", keyword);
        map.put("productType", productType);
        map.put("storageId", storageId);
        map.put("shopId", shopId);
        map.put("companyId", request.getParameter("companyId"));
        map.put("current", current);
        map.put("pageSize", size);
        return stockRecordService.getListPage(map);
    }

    @UserSessionRequired
    @GetMapping("/productListPage")
    @ApiOperation(value = "选择sku初始化", notes = "选择sku初始化")
    @ApiImplicitParams({@ApiImplicitParam(name = "companyId", value = "公司id"),
            @ApiImplicitParam(name = "productType", value = "产品类型"),
            @ApiImplicitParam(name = "goodQuantity", value = "可用量 大于0"),
            @ApiImplicitParam(name = "badQuantity", value = "破损 大于0 "),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "keyword", value = "关键字（模糊查询）"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小")})
    public PageResult productListPage(HttpServletRequest request) {

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String productType = request.getParameter("productType");
        String storageId = request.getParameter("storageId");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        String companyIdC = request.getParameter("companyId");
        String goodQuantity = request.getParameter("goodQuantity");
        String badQuantity = request.getParameter("badQuantity");

        if (StringUtils.isNotBlank(companyIdC)) {
            map.put("companyId", companyIdC);
        }
        map.put("productType", productType);
        if (StringUtils.isNotBlank(goodQuantity)) {
            map.put("goodQuantity", goodQuantity);
        }
        if (StringUtils.isNotBlank(badQuantity)) {
            map.put("badQuantity", badQuantity);
        }
        map.put("notRack", "1");
        map.put("keyword", keyword);
        map.put("storageId", storageId);
        map.put("current", current);
        map.put("pageSize", size);
        return productStockRackService.getProductListPage(map);
    }

    @UserSessionRequired
    @GetMapping("/updateInit/{id}")
    @ApiOperation(value = "编辑初始化", notes = "编辑初始化")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = OrderRepairDetailRes.class))
    public SingleResult updateInit(@PathVariable("id") Long id) {
        return service.updateInit(id);
    }


    @UserSessionRequired
    @PutMapping("")
    @ApiOperation(value = "维修订单编辑修改", notes = "维修订单编辑修改")
    public SingleResult update(@RequestBody @Validated OrderRepairUpdateReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功", service.update(req, userId));
    }

    @UserSessionRequired
    @PutMapping("deleteSku")
    @ApiOperation(value = "编辑时,删除单个sku 或 部件", notes = "维修订单编辑修改")
    public SingleResult deleteSku(@RequestBody @Validated DeleteSkuOrComponentReq req) {
        Long userId = getCurrentUserId();
        service.deleteSku(req, userId);
        return SingleResult.success();
    }


    //
//    @DeleteMapping("/{id}")
//    @ApiOperation(value = "根据id删除", notes = "根据id删除")
//    public SingleResult delete(@PathVariable("id") Long id) {
//        Long userId = getCurrentUserId();
//        return SingleResult.success("删除成功",service.delete(id,userId));
//    }
//
    @UserSessionRequired
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查看详情", notes = "根据id查看详情")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = OrderRepairDetailRes.class))
    public SingleResult detail(@PathVariable("id") Long id) {
        return SingleResult.success("查询成功", service.detail(id));
    }

    //
    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return service.pageInit();
    }

    //
//    @GetMapping("/list")
//    @ApiOperation(value = "查询", notes = "查询")
//    public SingleResult list(HttpServletRequest request){
//        Long companyId = getCompanyId();
//
//        Map<String, String> map = new HashMap<>();
//        String keyword = request.getParameter("keyword");
//        map.put("keyword", keyword);
//        return SingleResult.success("查询成功", service.getList(map));
//    }
//
    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiImplicitParams({@ApiImplicitParam(name = "keyword", value = "关键字搜索"),
            @ApiImplicitParam(name = "keyword", value = "关键字搜索"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "页大小"),
            @ApiImplicitParam(name = "status", value = "状态"),
            @ApiImplicitParam(name = "snNo", value = "sn码"),
            @ApiImplicitParam(name = "sku", value = "sku"),
            @ApiImplicitParam(name = "backNo", value = "退货单号"),
            @ApiImplicitParam(name = "customerNo", value = "客户单号"),
            @ApiImplicitParam(name = "storageId", value = "仓库id")})
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = OrderRepairPageRes.class))
    public PageResult listPage(HttpServletRequest request) {

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");

        String status = request.getParameter("status");
        String snNo = request.getParameter("snNo");
        String backNo = request.getParameter("backNo");
        String customerNo = request.getParameter("customerNo");
        String storageId = request.getParameter("storageId");
        String sku = request.getParameter("sku");

        map.put("sku", sku);
        map.put("keyword", keyword);
        map.put("current", current);
        map.put("pageSize", size);
        map.put("status", status);
        map.put("snNo", snNo);
        map.put("backNo", backNo);
        map.put("customerNo", customerNo);
        map.put("storageId", storageId);
        return service.getListPage(map);
    }


    @UserSessionRequired
    @PutMapping("markConfirm")
    @ApiOperation(value = "标记确认", notes = "标记确认")
    public SingleResult markConfirm(Long id) {
        Long userId = getCurrentUserId();
        service.markConfirm(id, userId);
        return SingleResult.success();
    }

    @UserSessionRequired
    @PutMapping("discard/{id}")
    @ApiOperation(value = "废弃", notes = "废弃")
    public SingleResult discard(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        service.discard(id, userId);
        return SingleResult.success();
    }


    @UserSessionRequired
    @PutMapping("beginRepair")
    @ApiOperation(value = "开始维修", notes = "开始维修")
    public SingleResult beginRepair(@RequestBody @Validated BeginRepairReq req) {
        Long userId = getCurrentUserId();
        service.beginRepair(req, userId);
        return SingleResult.success();
    }

    @UserSessionRequired
    @GetMapping("finishRepairInit")
    @ApiOperation(value = "维修完成初始化/无法维修初始化", notes = "维修完成初始化/无法维修初始化")
    @ApiResponses(@ApiResponse(code = 200, message = "" , response = FinishRepairInitRes.class))
    public SingleResult finishRepairInit(Long id, Integer type) {
        return SingleResult.success("", service.finishRepairInit(id, type));
    }

    @UserSessionRequired
    @GetMapping("beginRepairInit/{id}")
    @ApiOperation(value = "开始维修初始化", notes = "开始维修初始化")
    @ApiResponses(@ApiResponse(code = 200, message = "" , response = FinishRepairInitRes.class))
    public SingleResult beginRepairInit(@PathVariable("id") Long id) {
        return SingleResult.success("", service.beginRepairInit(id));
    }


    @UserSessionRequired
    @PutMapping("finishRepair")
    @ApiOperation(value = "维修完成", notes = "维修完成")
    public SingleResult finishRepair(@RequestBody @Validated FinishRepairReq req) {
        Long userId = getCurrentUserId();
        service.finishRepair(req, userId);
        return SingleResult.success();
    }


    @UserSessionRequired
    @PutMapping("cannotRepair")
    @ApiOperation(value = "无法维修", notes = "无法维修")
    public SingleResult cannotRepair(@RequestBody @Validated CannotRepairReq req) {
        Long userId = getCurrentUserId();
        service.cannotRepair(req, userId);
        return SingleResult.success();
    }


//    @UserSessionRequired
//    @PutMapping("finishIndicate")
//    @ApiOperation(value = "完成指示", notes = "完成指示")
//    public SingleResult finishIndicate(@RequestBody @Validated FinishIndicateReq req) {
//        Long userId = getCurrentUserId();
//        service.finishIndicate(req, userId);
//        return SingleResult.success();
//    }


    @UserSessionRequired
    @GetMapping("getPosition")
    @ApiOperation(value = "获取库位信息(完成指示)", notes = "获取库位信息(完成指示)")
    public SingleResult getPosition(Long storageId, Long companyId, Long productId, Integer type, Integer containBad) {
        return SingleResult.success("", storagePositionService.getPosition(storageId, companyId, productId, 0, type == null ? 0 : type, containBad == null ? 0 : containBad));
    }


    @UserSessionRequired
    @GetMapping("chargeInit")
    @ApiOperation(value = "收费初始化", notes = "收费初始化")
    public SingleResult chargeInit(Long id) {
        return SingleResult.success("", service.chargeInit(id));
    }

    @UserSessionRequired
    @PutMapping("charge")
    @ApiOperation(value = "收费", notes = "收费")
    public SingleResult charge(@RequestBody @Validated ChargeReq req) {
        Long userId = getCurrentUserId();
        service.charge(req, userId);
        return SingleResult.success();
    }



    @UserSessionRequired
    @PostMapping("/batchExportRepair")
    @ApiOperation(value = "批量导出维修单", notes = "批量导出维修单")
    public void batchExportRepair(@RequestBody @Validated BatchExportRepairReq req, HttpServletResponse response) throws IOException {
        service.batchExportRepair(req, getCurrentUserId(), response);
    }


    @UserSessionRequired
    @PostMapping("/printSnById")
    @ApiOperation(value = "导出维修单", notes = "导出维修单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "维修订单id", required = true, type = "arr")})
    public void printSnById(@RequestBody @Validated ExportRepairReq req, HttpServletResponse response) throws IOException {
        service.exportRepair(req, getCurrentUserId(), response);
    }

    @UserSessionRequired
    @GetMapping("/batchExportInit")
    @ApiOperation(value = "批量导出维修单初始化", notes = "导出SN")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "维修订单id", required = true, type = "arr")})
    public SingleResult batchExportInit(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String length = request.getParameter("length");
        String width = request.getParameter("width");
        String count = request.getParameter("count");
        String[] id = request.getParameterValues("id[]");
        return SingleResult.success(service.batchExportInit(id));
    }



    @UserSessionRequired
    @GetMapping("/printSn")
    @ApiOperation(value = "导出SN", notes = "导出SN")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "维修订单id", required = true, type = "arr")})
    public void printSn(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String length = request.getParameter("length");
        String width = request.getParameter("width");
        String count = request.getParameter("count");
        String[] id = request.getParameterValues("id[]");
        service.printSn(id, getCurrentUserId(), response);
    }


    @UserSessionRequired
    @GetMapping("/printSnSku")
    @ApiOperation(value = "导出单个sku SN码", notes = "导出单个sku SN码")
    @ApiImplicitParams({@ApiImplicitParam(name = "repairSkuId", value = "sku 信息记录id", required = true),
            @ApiImplicitParam(name = "id", value = "维修订单id", required = true)})
    public void printSnSku(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String length = request.getParameter("length");
        String width = request.getParameter("width");
        String count = request.getParameter("count");
        String id = request.getParameter("id");
        String repairSkuId = request.getParameter("repairSkuId");

        service.printSnSku(id, repairSkuId, getCurrentUserId(), response);
    }


}

